from django.shortcuts import render
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView
from drf_haystack.viewsets import HaystackViewSet

from .models import SKU
from . import serializers
# Create your views here.


class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    # 指定索引模型类
    index_models = [SKU]
    # 指定序列化器
    serializer_class = serializers.SKUIndexSerializer


# url(r'^categories/(?P<category_id>\d+)/skus/', views.SKUListView.as_view()),
class SKUListView(ListAPIView):
    """商品列表：排序和分页
    """
    # 指定序列化器
    serializer_class = serializers.SKUSerializer

    # 指定排序后端
    filter_backends = [OrderingFilter]
    # 指定排序的字段，由ordering接受
    ordering_fields = ('create_time', 'price', 'sales')

    # 指定查询集
    # queryset = SKU.objects.all()
    def get_queryset(self):
        category_id = self.kwargs.get('category_id')
        # 商品列表中的数据需要满足指定的分类和必须是上架的商品
        return SKU.objects.filter(category_id=category_id, is_launched=True)